window.serialSaveInfo = serialSaveInfo;
//初始化
var  serialSaveInfo = [];
// 创建 Proxy 对象 监听数组

function connectWebSocket(socket) {
    if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    } else {
        let curWwwPath = window.document.location.href;
        //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
        let pathName = window.document.location.pathname;
        let pos = curWwwPath.indexOf(pathName);
        //获取主机地址，如： http://localhost:8083
        let curPath = curWwwPath.substring(0, pos);
        console.log("您的浏览器支持WebSocket");
        //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
        var socketUrl = curPath + "/fmcode/ws/2" /*+ $("#userId").val()*/;
        socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
        console.log(socketUrl);
        if (socket != null) {
            socket.close();
            socket = null;
        }
        socket = new WebSocket(socketUrl);

        //打开事件
        socket.onopen = function () {
            console.log("websocket已打开");
            //socket.send("这是来自客户端的消息" + location.href + new Date());
        };

        //获得消息事件
        socket.onmessage = function (msg) {
            console.log("收到消息: " + msg.data);
            appendToConsole(msg.data);
            if (msg.data) {
                if (msg.data.indexOf("连接成功") < 0) {
                    serialSaveInfo.push(msg.data);
                }
            }
            console.log(serialSaveInfo);
        };

        //关闭事件
        socket.onclose = function () {
            console.log("websocket已关闭");
        }

        //发生了错误事件
        socket.onerror = function () {
            console.log("websocket发生了错误");
        }
    }
}
// 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，这样服务端会抛异常。

    window.onbeforeunload = function() {
    openOrCloseSerial(recom,false);
}
/*查询当前系统正在使用的串口*/
function selectSerials() {
    var recom = null;

    $.ajax({
        url: rootPath+"/serial/listPorts",
        type: 'GET',
        dataType: "json",
        contentType: "application/json",
        async: false,
        success: function (result) {
            res = result.data;
            console.log(result.data[0]);
            if(result.data.length > 0){
                recom = result.data[0]
            }
        }
    });
    return recom;
}

/*打开或关闭串口*/
//openState  为 true 则 打开，false关闭
function openOrCloseSerial(serial_port,openState) {
    var returnOpenSerial = "";
    var ws = null;
    if (openState) {
        url = rootPath+'/serial/openPort';
        send_data = {
            "portName": serial_port,
            "baudrate": "9600",
            "dataBits": "8",
            "stopBits": "1",
            "parity": "0"
        };
        connectWebSocket(ws);
    } else {
        url = rootPath+'/serial/closePort';
        send_data = {
            "portName": serial_port
        };
        if(ws !=null){
            ws.close();
        }
    }
    console.log(send_data);
    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        data: send_data,
        async: false,
        success: function (result) {
            if (result != null && result.code == 200) {
                     returnOpenSerial =result.msg;
                 }else{
                     returnOpenSerial =result.msg;
            }
        },
        error: function (err) {
            if (err != null) {
                returnOpenSerial =JSON.parse(err.responseText);
            }
        }
    });
    return  returnOpenSerial;


}

window.addEventListener('load', function () {
    const shouldRefresh = localStorage.getItem('shouldRefresh');
    if (shouldRefresh === 'true') {
        // 清除标识
        localStorage.removeItem('shouldRefresh');
        // 刷新页面
        location.reload();
    }
});